using UnityEngine;

namespace ViewController.Gameplay
{
    public class CameraController : MonoBehaviour
    {
        private readonly float _maxX = 5;
        private readonly float _maxY = 5;

        private readonly float _minX = -5;
        private readonly float _minY = -5;

        private Transform _playerTrans;

        private Vector3 _targetPos;

        private void Update()
        {
            if (!_playerTrans)
            {
                var playerGameObj = GameObject.FindWithTag("Player");

                if (playerGameObj)
                    _playerTrans = playerGameObj.transform;
                else
                    return;
            }

            var isRight = Mathf.Sign(_playerTrans.localScale.x);

            var playerPos = _playerTrans.position;

            _targetPos.x = playerPos.x + 3 * isRight;
            _targetPos.y = playerPos.y + 2;
            _targetPos.z = -10;

            var smoothSpeed = 5;

            // 增加一个平滑处理
            var position = transform.position;
            position = Vector3.Lerp(position, new Vector3(_targetPos.x, _targetPos.y, position.z),
                smoothSpeed * Time.deltaTime);

            // 锁定在一个固定区域
            transform.position = new Vector3(Mathf.Clamp(position.x, _minX, _maxX),
                Mathf.Clamp(position.y, _minY, _maxY), position.z);
        }
    }
}